package com.atguigu.tingshu.user.strategy;

import com.atguigu.tingshu.album.client.TrackInfoFeignClient;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.List;
@Component("1002")
public class TrackStrategy implements ItemTypeStrategy{
    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;
    @Autowired
    private TrackInfoFeignClient trackInfoFeignClient;

    @Override
    public void savePaidRecord(UserPaidRecordVo userPaidRecordVo) {
        List<Long> itemIdList = userPaidRecordVo.getItemIdList();
        LambdaQueryWrapper<UserPaidTrack> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(UserPaidTrack::getTrackId,itemIdList).eq(UserPaidTrack::getUserId,userPaidRecordVo.getUserId());
        List<UserPaidTrack> userPaidTrackList = userPaidTrackMapper.selectList(wrapper);
        if (!CollectionUtils.isEmpty(userPaidTrackList)){
            return;
        }
        Result<TrackInfo> trackInfoResult = trackInfoFeignClient.getTrackInfo(itemIdList.get(0));
        Assert.notNull("trackInfoResult", "远程调用声音服务失败");
        TrackInfo trackInfo = trackInfoResult.getData();
        Assert.notNull("trackInfo", "声音信息不存在");
        for (Long trackId : itemIdList) {
            UserPaidTrack userPaidTrack = new UserPaidTrack();
            userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
            userPaidTrack.setUserId(userPaidRecordVo.getUserId());
            userPaidTrack.setAlbumId(trackInfo.getAlbumId());
            userPaidTrack.setTrackId(trackId);
            userPaidTrackMapper.insert(userPaidTrack);
        }
}

}
